class Solution {
    int dx[4] = {0, 0, 1, -1};
    int dy[4] = {1, -1, 0, 0};
    bool vis[20][20];
    int m, n, ret, step = 2; // step是总共要走的步数，算上终点和起点
 
public:
    int uniquePathsIII(vector<vector<int>>& grid) {
        m = grid.size(), n = grid[0].size();
        int x = 0, y = 0;
        for(int i = 0; i < m; ++i)
        {
            for(int j = 0; j < n; ++j)
            {
                if(grid[i][j] == 0)
                    ++step; // 遇到一个0，要走的步数+1
                else if(grid[i][j] == 1)
                    x = i, y = j; // 记录起始位置
            }
        }
        vis[x][y] = true;
        dfs(grid, x, y, 1); // 起点算一个步数了
        return ret;
    }
 
    void dfs(vector<vector<int>>& grid, int i, int j, int cnt)
    {
        if(grid[i][j] == 2)
        {
            if(step == cnt)
                ++ret;
            return;
        }
        for(int k = 0; k < 4; ++k)
        {
            int x = i + dx[k], y = j + dy[k];
            if(x >= 0 && x < m && y >= 0 && y < n && grid[x][y] != -1 && !vis[x][y])
            {
                vis[x][y] = true;
                dfs(grid, x, y, cnt + 1);
                vis[x][y] = false;
            }
        }
    }
};